
from flask import Flask
from settings import DefaultConfig

import pymysql,json

app = Flask(__name__)

app.config.from_object(DefaultConfig)

user = app.config.get("MYSQL_USER")
password = app.config.get("MYSQL_PASSWORD")
host = app.config.get("MYSQL_HOST")
port = app.config.get("MYSQL_PORT")
name = app.config.get("MYSQL_DATABASE")
charset = app.config.get("MYSQL_CHARSET")

# mysql操作
class Mysql():
    def __init__(self,table):
        try:
            self.table = table
            self.pymysql_con = pymysql.connect(host=host,port=port,user=user,password=password,database=name,charset=charset)
            self.mysql = self.pymysql_con.cursor() # 创建游标对象
        except Exception as e:
            print("错误信息",e)
            print("连接数据库失败！")
        else:
            print("连接数据库成功！")
            self.now_table()

    # 创建表
    def now_table(self):
        try:
            sql = f"""
                create table {self.table}(
                    id int primary key auto_increment,
                    name varchar (20),
                    age int ,
                    sex enum("男","女")
                )
            """
            self.mysql.execute(sql)
        except Exception as e: # 创建失败 表存在
            pass
        else:
            print("创建表成功！")
    # 查询数据
    def select(self):
        try:
            sql = f"""select * from {self.table}"""
            self.mysql.execute(sql)
        except Exception as e:
            print(e)
            print("查询失败！")
        else:
            data = self.mysql.fetchall()
            return data

    # 添加数据
    def push_data(self,data):
        try:
            sql = f"""
                insert into {self.table} values
                ({data["id"]},'{data["name"]}',{data["age"]},{data["sex"]});
            """
            self.mysql.execute(sql)
        except Exception as e:
            self.pymysql_con.rollback()
            print(e)
            print("添加失败！")
            return False
        else:
            self.pymysql_con.commit()
            print("添加成功！")
            return True

    # 修改数据
    def up_data(self, data):
        try:
            sql = f"""
                update {self.table} set 
                name = '{data["name"]}',age = {data["age"]} ,sex = {data["sex"]} where id = {data["id"]}
            """
            self.mysql.execute(sql)
        except Exception as e:
            self.pymysql_con.rollback()
            print(e)
            print("修改失败！")
            return False
        else:
            self.pymysql_con.commit()
            print("修改成功！")
            return True

    # 删除数据的方法
    def del_data(self, data):
        try:
            sql = f"""
            delete from {self.table} where id = {data["id"]}
            """
            self.mysql.execute(sql)
        except Exception as e:
            self.pymysql_con.rollback()
            print(e)
            print("删除失败！")
            return False
        else:
            self.pymysql_con.commit()
            print("删除成功！")
            return True

# 视图
mysql = Mysql("student")

# 获取所有数据
@app.route("/",methods=["get"])
def list():
    data = mysql.select()
    if not data:# 没有查询到数据返回无
        return "没有数据"
    temp = []
    for i in data:
        dict1 = {"id":i[0],"name":i[1],"age":i[2],"sex":i[3]}
        temp.append(dict1)

    ser = json.dumps(temp,ensure_ascii=False)
    return ser

# 添加数据
@app.route("/add",methods=["get"])
def add_data():
    data = {"id": 1,"name": "阿萨德","age": 19,"sex": 1}
    code = mysql.push_data(data)
    if not code:# 添加失败
        return "添加失败！"

    ser = json.dumps(data,ensure_ascii=False)
    return ser

# 修改数据
@app.route("/update",methods=["get"])
def updata_data():
    data = {"id": 1,"name": "艾斯","age": 19,"sex": 2}
    code = mysql.up_data(data)
    if not code:# 修改失败
        return "修改失败！"

    ser = json.dumps(data,ensure_ascii=False)
    return ser

# 删除数据
@app.route("/del",methods=["delete"])
def del_data():
    data = {"id": 1}
    code = mysql.del_data(data)
    if not code:# 删除失败
        return "删除失败！"

    return "删除成功！"



if __name__ == '__main__':
    app.run()